package com.wmm.servlet;

import com.wmm.bean.User;
import com.wmm.service.UserService;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@javax.servlet.annotation.WebServlet(name = "Login_Servlet" ,urlPatterns = "/login")
public class Login_Servlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        // 1.获取请求中的用户名和密码信息并打印出来
        String userName = request.getParameter("userName");
        System.out.println("获取到的用户名为：" + userName);
        String password = request.getParameter("password");
        System.out.println("获取到的密码为：" + password);
        String freeLogin = request.getParameter("freeLogin");
        // 2.创建UserService类型的对象去实现数据的校验功能
        UserService userService = new UserService();
        User user = userService.userLoginService(new User(userName, password));
        if (null == user) {
            System.out.println("登录失败，用户名或密码错误！");
            request.setAttribute("error", "登录失败，用户名或密码错误！");
            // 实现服务器跳转  共享request和response对象
            //RequestDispatcher requestDispatcher = request.getRequestDispatcher("login.jsp");
            //requestDispatcher.forward(request, response);
        } else {
            HttpSession session = request.getSession();
            System.out.println("登录成功，欢迎使用！");
            // 将登录成功的用户信息放入session对象中实现多个请求共享
            session.setAttribute("user", user);
            if (null != freeLogin){
                if ("freeLogin".equals(freeLogin)){
                    Cookie cookie = new Cookie("user",userName+"-"+password);
                    cookie.setMaxAge(60*60*24*7);
                    response.addCookie(cookie);
                }
            }
            // 实现客户端跳转
            response.sendRedirect("findStudentByPage");
        }
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        this.doPost(request, response);
    }
}
